package com.xbts.system.service.impl;

import com.xbts.common.config.XbtsConfig;
import com.xbts.common.constant.Constants;
import com.xbts.common.core.text.CharsetKit;
import com.xbts.common.enums.EmailTypeEnum;
import com.xbts.common.exception.ServiceException;
import com.xbts.common.utils.StringUtils;
import com.xbts.system.domain.CnEmailTemplate;
import com.xbts.system.domain.dto.EmailSendDTO;
import com.xbts.system.service.ICnEmailTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;

/**
 * @author : llk
 * @Date: 2023/12/28 11:13
 */
@Service
@Slf4j
public class EmailSendService {

    @Value("${spring.mail.username}")
    private String from;

    @Autowired(required = false)
    private JavaMailSender javaMailSender; // 引入Spring Mail依赖后，会自动装配到IOC容器
    @Autowired
    private ICnEmailTemplateService emailTemplateService;

    /**
     * 发送邮件
     *
     * @param email 邮箱
     */
    public void sendFile(String email, String subject, String fileUrl) {
        MimeMessage message = javaMailSender.createMimeMessage();
        String[] split = fileUrl.split(",");

        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true, CharsetKit.UTF_8);
            helper.setFrom(from);
            helper.setTo(email);
            helper.setSubject(subject);
            helper.setText("");
            for (int i = 0; i < split.length; i++) {
                if (StringUtils.isNotEmpty(split[i])) {
                    // 本地资源路径
                    String localPath = XbtsConfig.getProfile();
                    // 数据库资源地址
                    String downloadPath = localPath + StringUtils.substringAfter(split[i], Constants.RESOURCE_PREFIX);
                    FileSystemResource resource = new FileSystemResource(downloadPath);

                    String[] split2 = downloadPath.split("\\.");
                    helper.addAttachment("发票附件" + i + "." + split2[split2.length - 1], resource);
                }
            }
            javaMailSender.send(message);
            log.info("发送邮件成功, 邮箱为: {}", email);
        } catch (Exception e) {
            log.error("发送邮件失败: ", e);
        }
    }

    /**
     * 发送邮件
     *
     * @param emailSendDTO 邮件发送实体类
     */
    public void sendMessage(EmailSendDTO emailSendDTO) {
        String email = emailSendDTO.getEmail();
        if (StringUtils.isEmpty(email)) {
//            throw new ServiceException("邮箱不能为空");
            return;
        }
        try {
            MimeMessage message = javaMailSender.createMimeMessage();

            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true, CharsetKit.UTF_8);
            helper.setFrom(from);
            helper.setTo(email);
            helper.setSubject(emailSendDTO.getSubject());
            helper.setText(getSendContent(emailSendDTO));
            javaMailSender.send(message);
            log.info("发送邮件成功, 邮箱为: {}", email);
        } catch (Exception e) {
            log.error("发送邮件失败: ", e);
        }
    }

    private String getSendContent(EmailSendDTO emailSendDTO) {
        // 获取邮件模板内容
        CnEmailTemplate emailTemplate = emailTemplateService.lambdaQuery().eq(CnEmailTemplate::getType, emailSendDTO.getTypeEnum().name()).one();
        String templateContent = emailTemplate.getContent();
        String[] content = emailSendDTO.getContent();

        for (int i = 0; i < content.length; i++) {
            templateContent = templateContent.replace("{" + (i) + "}", content[i]);
        }
        return templateContent;
    }
}
